//
//  ZJRecorder.m
//  SoundRecording
//
//  Created by zhengju on 2017/11/29.
//  Copyright © 2017年 郑俱. All rights reserved.
//

#import "ZJRecorder.h"

@interface ZJRecorder()<NSCopying,NSMutableCopying,AVAudioRecorderDelegate>

@property(strong,nonatomic) NSURL * recorderUrl;
@property(strong,nonatomic) NSTimer * timer;

@end

@implementation ZJRecorder
+ (instancetype)shareRecorder{
  static  ZJRecorder * recorder = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        recorder = [[super allocWithZone:NULL]init];
        
    });
    return recorder;
}
+(instancetype)allocWithZone:(struct _NSZone *)zone{
    return [ZJRecorder shareRecorder];
}
- (id)copyWithZone:(NSZone *)zone{
    return [ZJRecorder shareRecorder];
}
- (id)mutableCopyWithZone:(NSZone *)zone{
    return [ZJRecorder shareRecorder];
}

- (instancetype)init{
    if(self = [super init]){
        
        
    }
    return self;
    
}

- (void)setAudioSession{
    AVAudioSession * session = [AVAudioSession sharedInstance];
    NSError * setCategoryError = nil;
    [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&setCategoryError];
    NSError * activationError = nil;
    [session setActive:YES error:&activationError];
    
}

- (NSURL *)getRecordAudioPath:(NSString *)urlPath{
    NSURL *url=[NSURL fileURLWithPath:urlPath];
    return url;
}
/**
 *  取得录音文件设置
 *
 *  @return 录音设置
 */
-(NSDictionary *)getAudioSetting{
    NSMutableDictionary * dicM = [NSMutableDictionary dictionary];
    //设置录音格式
    [dicM setObject:@(kAudioFormatLinearPCM) forKey:AVFormatIDKey];
    //设置录音采样率，8000是电话采样率，对于一般录音已经够了
    [dicM setObject:@(8000) forKey:AVSampleRateKey];
    //设置通道，这里采用单声道
    [dicM setObject:@(2) forKey:AVNumberOfChannelsKey];
    //每个采样点位数，分为8、16、24、43
    [dicM setObject:@(8) forKey:AVLinearPCMBitDepthKey];
    //是否使用浮点数采样
    [dicM setObject:@(YES) forKey:AVLinearPCMIsFloatKey];
    //音频质量,采样质量
    [dicM setValue:[NSNumber numberWithInt:AVAudioQualityMin] forKey:AVEncoderAudioQualityKey];
    //录音的质量
    [dicM setValue:[NSNumber numberWithInt:AVAudioQualityHigh] forKey:AVEncoderAudioQualityKey];
    return dicM;
}
- (void)setRecorder{
    NSError * err  = nil;
    //创建录音格式设置
    NSDictionary *setting=[self getAudioSetting];
    
    _recorder = [[AVAudioRecorder alloc]initWithURL:self.recorderUrl settings:setting error:&err];
    _recorder.delegate = self;
    //如果要监控声波必须设置为YES
    _recorder.meteringEnabled = YES;
    [_recorder updateMeters];//刷新音量数据
    if(err){
        NSLog(@"创建录音机对象时发生错误，错误信息：%@",err.localizedDescription);
        _recorder = nil;
        
    }
    [_recorder prepareToRecord];
    
}
- (void)recorderSetPath:(NSString *)urlPath{
    self.recorderUrl = [self getRecordAudioPath:urlPath];
}

- (void)recorderStart{
    
    [self setRecorder];
    
    NSLog(@"开始录音");
    
    [self setAudioSession];
    
    [self.recorder record];
    
   // self.timer = [NSTimer scheduledTimerWithTimeInterval: 0.3 target: self selector: @selector(levelTimerCallback:) userInfo: nil repeats: YES];
    
}
- (void)recorderPause{
    if([self.recorder isRecording]){
        NSLog(@"已停止");
        [self recorderStop];
    }else{
        NSLog(@"开始录音");

        [self recorderStart];
        
    }
}
- (void)recorderStop{
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];  //此处需要恢复设置回放标志，否则会导致其它播放声音也会变小
    [session setActive:YES error:nil];

    [self.recorder stop];
    self.recorder.delegate = nil;
    self.recorder = nil;
    [self.timer invalidate];
    self.timer = nil;
}

#pragma mark --AVAudioRecorderDelegate
- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag{
    
    NSLog(@"录音完成!");
}
-(void)audioRecorderEncodeErrorDidOccur:(AVAudioRecorder* )recorder error:(NSError* )error
{
    NSLog(@"录音出错!");
    
}

@end
